<template>
  <div class="form-container">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
    >
      <el-form-item label="楼宇" prop="buildingId">
        <el-select v-model="ruleForm.buildingId" placeholder="请选择楼宇">
          <el-option
            v-for="item in buildingList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>

      <el-form-item label="几人间" prop="type">
        <el-select v-model="ruleForm.type" placeholder="请选择几人间">
          <el-option label="4人间" value="4" />
          <el-option label="6人间" value="6" />
          <el-option label="8人间" value="8" />
          <el-option label="10人间" value="10" />
        </el-select>
      </el-form-item>

      <el-form-item label="联系电话" prop="telephone">
        <el-input v-model="ruleForm.telephone" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">立即创建</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ElMessageBox } from 'element-plus'
import {dormitoryApi} from '@/api/dormitory'
import { buildingApi} from '@/api/buildings'

export default {
  data() {
    return {
      ruleForm: {
        buildingId: '',
        name: '',
        type: '',
        telephone: ''
      },
      buildingList: [],
      rules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择几人间', trigger: 'change' }
        ],
        telephone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          dormitoryApi.saveDormitory(this.ruleForm).then((resp) => {
            if (resp.code === 0) {
                ElMessageBox.alert(`${this.ruleForm.name} 添加成功`, '', {
                    confirmButtonText: '确定',
                    callback: () => {
                        this.$router.push('/dormitoryManager')
                    }
                })
            } else {
                this.$message.error(resp.msg || '添加失败')
            }
        }).catch(() => {
            this.$message.error('添加失败')
        })
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    }
  },
  created() {
    buildingApi.getBuildingList().then((resp) => {
      this.buildingList = resp.data.data
    })
  }
}
</script>

<style scoped>
.form-container {
  margin: 60px auto;
  width: 400px;
  padding: 20px;
}
</style>
